<template>
  <!-- 增改用户弹框 -->
  <hcDialog
    dialogWidth="600px"
    :dialogTitle="options.type === 'add' ? '新增物料' : '编辑物料'"
    :isVisable="options.show"
    @closeDialog="closeFun"
    @openDialog="openFun"
  >
    <el-form
      ref="formRef"
      :model="form"
      label-width="6vw"
      status-icon
      :rules="rules"
      :validate-on-rule-change="false"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="物料类型" prop="materialType">
            <el-select
              v-model="form.materialType"
              placeholder="物料类型"
              :disabled="options.type === 'edit'"
            >
              <el-option
                v-for="item of Material"
                :label="item.label"
                :value="item.code"
                :key="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="物料名称" prop="materialName">
            <el-input v-model="form.materialName" placeholder="物料名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料料号" prop="materialCode">
            <el-input v-model="form.materialCode" placeholder="物料料号" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            label="物料长度"
            prop="length"
            title="物料图像水平方向尺寸"
          >
            <el-input-number v-model="form.length" placeholder="物料长度/mm" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="物料宽度"
            prop="width"
            title="物料图像竖直方向尺寸"
          >
            <el-input-number v-model="form.width" placeholder="物料宽度/mm" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料高度" prop="height">
            <el-input-number v-model="form.height" placeholder="物料高度/mm" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="重量" prop="weight">
            <el-input-number v-model="form.weight" placeholder="重量/g" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="色点" prop="colorSpot">
            <el-input-number v-model="form.colorSpot" placeholder="色点" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="直径" prop="diameter">
            <el-input-number v-model="form.diameter" placeholder="直径/mm" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="尺寸" prop="size">
            <el-input v-model="form.size" placeholder="尺寸/寸" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="厚度" prop="thickness">
            <el-input-number v-model="form.thickness" placeholder="厚度/mm" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="物料描述" prop="description">
            <el-input v-model="form.description" placeholder="物料描述" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="物料图片"
            prop="imgPath"
            title="图片用于编辑界面展示，请上传清晰图片，物料填充整个图片，不留边距"
          >
            <div class="upload-item" v-loading="uploading">
              <el-upload
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleChange1"
              >
                <el-button icon="plus" type="primary"
                  >上传物料正面图片</el-button
                >
              </el-upload>
              <img
                :src="baseUrl + form.imgPath[0]"
                class="img"
                v-show="form.imgPath[0]"
              />
            </div>
            <div
              class="upload-item"
              v-loading="uploading"
              v-show="twoImgCode.includes(form.materialType)"
            >
              <el-upload
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleChange2"
              >
                <el-button icon="plus" type="primary"
                  >上传物料反面图片</el-button
                >
              </el-upload>
              <img
                :src="baseUrl + form.imgPath[1]"
                class="img"
                v-show="form.imgPath[1]"
              />
            </div>
            <div class="tip" v-show="twoImgCode.includes(form.materialType)">
              请检查正反面图片无误
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <div class="btns">
          <el-button type="primary" @click="saveDialog()">保存</el-button>
          <el-button @click="closeFun">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </hcDialog>
</template>

<script setup name="UserDialog">
import { watch, reactive, ref } from "vue";
import { Material } from "@/store/editStore";
import { postMaterial, putMaterial, postMaterialImg } from "@/api/specs";
import getEnvConfig from "@/config/axios/getEnvConfig";

let baseUrl = getEnvConfig.VITE_BASE_URL.replace("api", "");

const emit = defineEmits(["closeDialog"]);

const props = defineProps({
  options: {
    type: Object,
    default: () => {
      return {
        show: false,
        type: "add", // 用于判断是编辑还是删除 add edit
        data: null, // 当前编辑的用户
      };
    },
  },
});
let twoImgCode = [0, 7];
const formRef = ref();
const uploading = ref(false);
const form = reactive({
  id: "",
  materialType: "",
  materialName: "",
  materialCode: "",
  length: null,
  width: null,
  height: null,
  weight: null,
  colorSpot: null,
  diameter: null,
  size: null,
  thickness: null,
  description: "",
  imgPath: [],
});

const defaultRules = {
  materialType: [
    { required: true, message: "请选择物料类型", trigger: "change" },
  ],
  materialCode: [
    { required: true, message: "请输入物料料号", trigger: "blur" },
  ],
  materialName: [
    { required: true, message: "请输入物料名称", trigger: "blur" },
  ],
};
const othRules = {
  length: [{ required: true, message: "请输入长度", trigger: "blur" }],
  width: [{ required: true, message: "请输入宽度", trigger: "blur" }],
  height: [{ required: true, message: "请输入高度", trigger: "blur" }],
  weight: [{ required: true, message: "请输入重量", trigger: "blur" }],
  colorSpot: [{ required: true, message: "请输入颜色", trigger: "blur" }],
  diameter: [{ required: true, message: "请输入直径", trigger: "blur" }],
  size: [{ required: true, message: "请输入尺寸", trigger: "blur" }],
  thickness: [{ required: true, message: "请输入厚度", trigger: "blur" }],
};
let rules = ref(defaultRules);

function handleChange1(file) {
  uploadImg(file, 0);
}
function handleChange2(file) {
  uploadImg(file, 1);
}

async function uploadImg(file, index) {
  try {
    uploading.value = true;
    let filedata = new FormData();
    filedata.append("formFiles", file.raw);
    let res = await postMaterialImg(filedata);
    if (res) {
      form.imgPath[index] = res.replace(",", "").replace(/\\/g, "/");
    }
    uploading.value = false;
  } catch (e) {
    ElMessage.error("上传失败");
    uploading.value = false;
  }
}

function saveDialog() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (!twoImgCode.includes(form.materialType)) {
        if (!form.imgPath[0]) {
          ElMessage.warning("请上传物料图片");
          return;
        }
      } else {
        if (!form.imgPath[0] || !form.imgPath[1]) {
          ElMessage.warning("请上传物料正反面图片");
          return;
        }
      }

      let res = "";
      form.imgPath = form.imgPath.join(",");
      if (props.options.type === "edit") {
        res = await putMaterial(form);
      } else {
        res = await postMaterial(form);
      }
      if (res) {
        ElMessage.success("保存成功");
        emit("closeDialog", true);
      } else {
        ElMessage.error("保存失败");
      }
    }
  });
}

// 关闭弹框
const closeFun = () => {
  formRef.value?.resetFields();
  form.imgPath = [];
  emit("closeDialog");
};

function openFun() {
  if (props.options.type === "edit") {
    for (let key in form) {
      if (key === "imgPath") {
        form[key] = props.options.data[key].split(",");
      } else {
        form[key] = props.options.data[key];
      }
    }
  }
}

watch(
  () => form.materialType,
  (val) => {
    rules.value = JSON.parse(JSON.stringify(defaultRules));
    switch (val) {
      case 0:
        rules.value.diameter = othRules.diameter;
        rules.value.size = othRules.size;
        rules.value.thickness = othRules.thickness;
        break;
      case 7:
        rules.value.length = othRules.length;
        rules.value.width = othRules.width;
        break;
      case 8:
        rules.value.length = othRules.length;
        rules.value.width = othRules.width;
        rules.value.height = othRules.height;
        break;
      case 9:
        rules.value.length = othRules.length;
        rules.value.width = othRules.width;
        rules.value.weight = othRules.weight;
        break;
      case 10:
        rules.value.length = othRules.length;
        rules.value.width = othRules.width;
        rules.value.colorSpot = othRules.colorSpot;
    }
  }
);
</script>

<style lang="scss" scoped>
.el-input-number {
  width: 100%;
}
.upload-item {
  width: 100%;
  height: 60px;
  display: flex;
  margin-bottom: 5px;
  .up {
    width: 60px;
    height: 60px;
    border: 1px solid;
  }
  .img {
    width: 60px;
    height: 60px;
    margin-left: 20px;
  }
}
.tip {
  font-size: 14px;
  color: orangered;
}
</style>
